const template = document.createElement("template");

template.innerHTML = /*html*/ `
<style>
:host {
  --height: 25px;
  --round-width: calc(var(--height) * 0.8);
  --padding:  calc(var(--height) * 0.2);
  display: inline-block;
  width: 50px;
  height: var(--height);
}

.liu-switch-box {
  width: 100%;
  height: 100%;
  background-color: rgb(220, 223, 230);
  border-radius: calc(var(--height) / 2);
  position: relative;
  transition: all 0.2s;
}

.liu-switch-box .liu-switch-round {
  content: "";
  position: absolute;
  top: 0;
  left: var(--padding);
  bottom: 0;
  margin: auto;
  width: var(--round-width);
  height: var(--round-width);
  background-color: rgb(255, 255, 255);
  border-radius: 50%;
  transition: all 0.3s;
}

input[type="checkbox"]:checked + .liu-switch-box {
  background-color: rgb(107, 44, 255);
}
input[type="checkbox"]:checked + .liu-switch-box .liu-switch-round {
  left: calc(100% - var(--round-width) - var(--padding));
}

input[type="checkbox"] {
  display: none;
}
</style>

<label>
<input type="checkbox" />
<div class="liu-switch-box"><div class="liu-switch-round"></div></div>
</label>
`;


export default class LiSwitch extends HTMLElement {
  static observedAttributes = ["width", "height", "checked"];
  constructor() {
    super();

    const shadow = this.attachShadow({ mode: "closed" });
    const content = template.content.cloneNode(true);
    this.input = content.querySelector("input");
    this.roundEl = content.querySelector(".liu-switch-round");
    this.input.addEventListener("change", (e) => {
      this.checked = e.target.checked;
      this.dispatchEvent(
        new CustomEvent("change", {
          detail: {
            checked: e.target.checked,
          },
        })
      );
    });

    shadow.appendChild(content);
  }

  attributeChangedCallback(name, oldValue, newValue) {
    if (name == "width" || name == "height") {
      let padding = newValue * 0.2;
      let width = newValue * 0.8;

      if (name == "width") this.style.width = newValue + "px";

      if (name == "height") {
        this.style.setProperty("--height", newValue + "px");;
        this.style.setProperty("--round-width", width + "px");
        this.style.setProperty("--padding", padding + "px");
      }
    }

    if(name == 'checked'){
      let bool = newValue === 'true';
      this.checked = bool;
      this.input.checked = bool;
    }
  }
}